<?php


namespace app\admin\controller;


use app\common\controller\AdminController;
use app\model\Article as ArticleModel;
use think\App;

/**
 * @ControllerAnnotation(title="文章管理")
 */
class Article extends AdminController
{
    public ?ArticleModel $model = null;

    public function __construct(App $app)
    {
        $this->model = new ArticleModel();
        parent::__construct($app);
    }

    /**
     * @NodeAnotation(title="文章列表")
     */
    public function articleList()
    {

        $rows = $this->model->select()->toArray();
        $rows = array_format_key($rows, 'type');
        $list = [];
        foreach (ArticleModel::$type_name as $key => $val) {
            $list[] = [
                'type'=> $key,
                'type_name'=> $val,
                'title'=> $rows[$key]['title'] ?? '',
                'content'=> $rows[$key]['content'] ?? '',
                'update_at'=> $rows[$key]['update_at'] ?? '',
            ];
        }

        $res = [
            'list'=> $list,
        ];
        $this->success($res);
    }

    /**
     * @NodeAnotation(title="编辑文章")
     */
    public function articleEdit()
    {
        $data['type'] = input('type', 0, 'int');
        $data['title'] = input('title', '', 'trim');
        $data['content'] = input('content', '', 'trim');

        // 验证
        $this->validate($data,[
            'type|类型' => 'require',
            'title|标题' => 'require',
            'content|内容' => 'require',
        ]);

        if (!isset(ArticleModel::$type_name[$data['type']])) {
            $this->error('类型不合法');
        }

        $id = $this->model->where('type', $data['type'])->value('id');

        if ($id) {
            $this->model->where('id', $id)->update($data);
        } else {
            $this->model->insert($data);
        }

        $this->success([],'保存成功');
    }
}